<template>
  <a-upload
    :action="action"
    :fileList="file ? [file] : []"
    :show-file-list="false"
    @change="onChange"
    @progress="onProgress"
    @success="onSuccess"
  >
    <template #upload-button>
      <div class="arco-upload-list-picture custom-upload-avatar" v-if="!file && image">
        <img :src="image" />
        <div class="arco-upload-list-picture-mask">
          <IconEdit />
        </div>
      </div>
      <div
        v-else
        :class="`arco-upload-list-item${
            file && file.status === 'error' ? ' arco-upload-list-item-error' : ''
          }`"
      >
        <div class="arco-upload-list-picture custom-upload-avatar" v-if="file && file.url">
          <img :src="file.url" />
          <div class="arco-upload-list-picture-mask">
            <IconEdit />
          </div>
          <a-progress
            v-if="file.status === 'uploading' && file.percent < 100"
            :percent="file.percent"
            type="circle"
            size="mini"
            class="progress"
          />
        </div>
        <div class="arco-upload-picture-card" v-else>
          <div class="arco-upload-picture-card-text">
            <IconPlus />
          </div>
        </div>
      </div>
    </template>
  </a-upload>
</template>

<script>
import IconEdit from "@arco-design/web-vue/es/icon/icon-edit";
import IconPlus from "@arco-design/web-vue/es/icon/icon-plus";
import { ref } from "vue";
export default {
  props: {
    image: {
      type: String,
      default: ""
    }
  },
  components: { IconPlus, IconEdit },
  setup(props, content) {
    const action = ref(import.meta.env.VITE_BASE_API + "/upload");
    const file = ref();

    const onChange = (_, currentFile) => {
      file.value = {
        ...currentFile
      };
    };
    const onProgress = currentFile => {
      file.value = currentFile;
    };
    const onSuccess = currentFile => {
      content.emit("getUrl", currentFile.response.url);
    };
    return {
      action,
      file,
      onChange,
      onProgress,
      onSuccess
    };
  }
};
</script>

<style lang="scss" scoped>
.progress {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
}
</style>